﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PeoplesJukebox.Core.Interfaces;
using PeoplesJukebox.Core.MediaItems;
using System.Threading;
using System.IO;

namespace PeoplesJukebox.Core.Players
{
    public class StubPlayer : IMediaPlayer
    {
        private Track _currentTrack;
        private static StubAudio _audio;

        public Track CurrentTrack
        {
            get { return _currentTrack; }
        }

        public void Start()
        {
            this.PlayNext();
        }

        private void PlayNext()
        {
            Track nextTrack = PeoplesJukeboxService.GetNextTrack();
            if (nextTrack != null)
            {
                //TODO - add logging
                try
                {
                    this.Stop();
                    _audio = new StubAudio();
                    _audio.TrackName = nextTrack.Name;
                    _audio.Ending += new PeoplesJukebox.Core.Players.StubAudio.OnEndingEventHandler(OnAudioEnding);
                    _audio.Play();
                }
                catch (Exception ex)
                {
                }
                this._currentTrack = nextTrack;
            }
        }

        public void Skip()
        {
            this.PlayNext();
        }

        public void Stop()
        {
            if (_audio != null)
            {
                _audio.Ending -= OnAudioEnding;
                _audio = null;
            }
        }

        void OnAudioEnding()
        {
            this.PlayNext();
        }
    }

    public class StubAudio
    {
        public delegate void OnEndingEventHandler();
        public event OnEndingEventHandler Ending;

        public string TrackName {get; set;}

        public void Play()
        {
            ThreadPool.QueueUserWorkItem(Play);
        }

        private void Play(object state)
        {
            File.AppendAllText(@"c:\temp\StubPlayer.txt", string.Format("{0}, played: {1}{2}", DateTime.Now, TrackName, Environment.NewLine));
            Thread.Sleep(90000);
            if (Ending != null)
            {
                Ending();
            }
        }
    }
}
